package contactbook.dao.impl;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import contactbook.dao.AccountDAOInterface;
import contactbook.model.Account;

@Stateless
@Local(AccountDAOInterface.class)
public class AccountDAO implements AccountDAOInterface {

	private static final String FIND_BY_LOGIN_PASSWORD = "SELECT a FROM Account a WHERE a.login = :login AND a.password = :password";
	
	@PersistenceContext(unitName = "ContactBookPU")
	protected EntityManager em;
	
	public AccountDAO() {}
	
	@Override
	public Account create(Account account) {
		em.persist(account);
		return account;
	}

	@Override
	public void delete(int accountId) {
		Account account = em.find(Account.class, accountId);
		em.remove(account);
	}
	
	@Override
	public Account findById(int accountId) {
		Account account = em.find(Account.class, accountId);
		return account;
	}
	
	@Override
	public Account findByLoginPassword(String login, String password) {
		Query q = em.createQuery(FIND_BY_LOGIN_PASSWORD);
		q.setParameter("login", login);
		q.setParameter("password", password);
		try {
			return (Account) q.getSingleResult();
		}
		catch (NoResultException ex) {
			return null;
		}
	}
	
	@Override
	public void update(Account account) {
		em.merge(account);
		em.flush();
	}
	
	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
}
